package com.horizon.mobile.searchdialog;

import java.util.ArrayList;
import java.util.List;

import zuo.biao.library.manager.HttpManager.OnHttpResponseListener;
import zuo.biao.library.util.JSON;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.horizon.mobile.R;
import com.horizon.mobile.adapter.SearchUserListAdapter;
import com.horizon.mobile.manage.SharePreferences;
import com.horizon.mobile.model.Agent;
import com.horizon.mobile.model.Result;
import com.horizon.mobile.model.SearchUser;
import com.horizon.mobile.util.HttpRequest;
/**
 * 人员搜索界面
 */
public class SearchAct extends Activity {
	private AutoCompleteTextView searchEdit;
	private Button searchBtn;
	private String str_search;
	private ListView userListLv;
	List<SearchUser> list = new ArrayList<SearchUser>();
	SearchUserListAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.dialog_search);

		 WindowManager m = getWindowManager();
		 Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高
		 LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
		 p.width = (int) (d.getWidth() * 1.0); // 宽度设置为屏幕的0.8
		 p.alpha = 1.0f; // 设置本身透明度
		 p.dimAmount = 0.0f; // 设置黑暗度
		
		 getWindow().setAttributes(p); // 设置生效
		 getWindow().setGravity(Gravity.TOP); // 设置靠右对齐
		init();
	}

	private void init() {
		// 搜索实例化
		searchEdit = (AutoCompleteTextView) findViewById(R.id.main_auto);
		initAutoComplete("history", searchEdit);
		searchBtn = (Button) findViewById(R.id.searchBtn);
		searchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchGoods();
			}
		});
		userListLv = (ListView) findViewById(R.id.userListLv);

	}

	/**
	 * 
	 * 初始化AutoCompleteTextView，使 AutoCompleteTextView在一开始获得焦点时自动提示
	 * 
	 * @param field
	 * 
	 * 
	 *            保存在sharedPreference中的字段名
	 * 
	 * @param autoCompleteTextView
	 * 
	 *            要操作的AutoCompleteTextView
	 */

	private void initAutoComplete(String field,
			final AutoCompleteTextView searchEdit) {

		SharedPreferences sp = getSharedPreferences("user_search", 0);

		String longhistory = sp.getString("history", "       没有搜索记录");

		// 将longhistory进行分割
		final String[] histories = longhistory.split(",");

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.search_history, histories);

		// 只保留最近的20条的记录

		if (histories.length > 20) {

			String[] newHistories = new String[20];

			System.arraycopy(histories, 0, newHistories, 0, 20);

			adapter = new ArrayAdapter<String>(this, R.layout.search_history,
					newHistories);

		}

		searchEdit.setAdapter(adapter);
		searchEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {

				AutoCompleteTextView view = (AutoCompleteTextView) v;
				if (hasFocus) {
					view.showDropDown();
				}

			}

		});

	}

	/**
	 * 搜索商品方法
	 */
	private void searchGoods() {
		saveHistory("history", searchEdit);
		HttpRequest.searchUser(
				SharePreferences.getInstance(SearchAct.this).getToken(), searchEdit
						.getText().toString(), 0, searchUserListener);

	}

	/**
	 * 
	 * 把指定AutoCompleteTextView中内容保存到sharedPreference中指定的字符段
	 * 
	 * @param field
	 * 
	 *            保存在sharedPreference中的字段名
	 * 
	 * @param autoCompleteTextView
	 * 
	 *            要操作的AutoCompleteTextView
	 */

	private void saveHistory(String field, final AutoCompleteTextView searchEdit) {

		String text = searchEdit.getText().toString();

		SharedPreferences sp = getSharedPreferences("user_search", 0);

		String longhistory = sp.getString(field, "");

		if (!longhistory.contains(text + ",")) {

			StringBuilder sb = new StringBuilder(longhistory);

			sb.insert(0, text + ",");

			sp.edit().putString("history", sb.toString()).commit();

		}

	}



	OnHttpResponseListener searchUserListener = new OnHttpResponseListener() {

		@Override
		public void onHttpResponse(int requestCode, String resultJson,
				Exception e) {
			// TODO Auto-generated method stub
			boolean isNull = resultJson == null;
			if (resultJson != null) {
				Result result = JSON.parseObject(resultJson, Result.class);
				if (result.isSuccess()) {
					list = JSON.parseArray(result.getData()
							.toString(), SearchUser.class);
					adapter = new SearchUserListAdapter(SearchAct.this, list);
					userListLv.setAdapter(adapter);
					userListLv.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int  position, long id) {
							
							Intent intent = new Intent();
					        Bundle bundle = new Bundle();
					        bundle.putString("userName",list.get(position).getName());
					        bundle.putString("userId",list.get(position).getId());
					        intent.putExtras(bundle);
					        setResult(RESULT_OK, intent);
					        finish();
						}
					
					});
				} else {
					//showShortToast(result.getMessage());
					Toast.makeText(SearchAct.this, "搜索出现问题！", Toast.LENGTH_SHORT).show();
				}
				
			}
			
			
		}
	};
	
	
}
